<template>
  <div class="add-box">
    <div class="permiss-box">
      <span class="title">角色权限预览</span>
      <el-form
        ref="roleForm"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input
            v-model="formData.roleCode"
            :disabled="popConfig.popType === 'edit'"
            maxlength="64"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            maxlength="500"
            resize="none"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="permiss-box">
      <span class="title">功能权限</span>
      <div class="header-box">
        <el-checkbox
          v-model="isSelectAll"
          class="mt-10"
          @change="selectAll('myTree')"
          >全选/全不选</el-checkbox
        >
        <el-checkbox v-model="isExpand" @change="expandAll('myTree')"
          >展开/折叠</el-checkbox
        >
      </div>
      <div class="menu-info">
        <el-tree
          ref="myTree"
          v-loading="loading"
          show-checkbox
          default-expand-all
          node-key="menuCode"
          :data="treeData"
          :props="menuDefaultProps"
        />
        <!-- :default-expanded-keys="menuDefaultOpen" -->
        <!-- :default-checked-keys="menuDefaultChecked" -->
      </div>
    </div>
  </div>
</template>

<script>
import { arr2tree } from '@/utils'
import { dictMixin } from '@/mixin/dict'
import { elementMixin } from '@/mixin/element'

export default {
  name: 'AddTenantRole',
  mixins: [dictMixin, elementMixin],
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        roleName: '',
        roleCode: '',
        remark: '',
        menuList: []
      },
      // 菜单权限参数
      loading: false,
      menuDefaultProps: {
        children: 'children',
        label: 'menuName'
      },
      menuDefaultChecked: [],
      treeData: [],
      menuDefaultOpen: [],
      dictOptions: [],
      // 数据权限参数
      deptLoading: false,
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            required: true,
            message: '角色名称长度过长',
            max: 24,
            trigger: 'blur'
          }
        ],
        roleCode: [
          { required: true, message: '请输入角色代码', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        if (data) {
          this.queryDetail(data)
        }
      },
      deep: true,
      immediate: true
    },
    confirm: {
      handler(confirm) {
        this.submit()
      }
    },
    treeData: {
      handler(val) {
        if (val && val.length) {
          this.$refs.myTree.setCheckedKeys([]) // 先清空选中
          this.$nextTick(() => {
            const that = this
            that.menuDefaultChecked.forEach((i, n) => {
              that.$refs.myTree.setChecked(that.menuDefaultChecked[n], true)
            })
          })
        }
      },
      deep: true
    }
  },
  created() {
    this.queryAllMenu()
  },
  methods: {
    // 查询详情
    async queryDetail(params) {
      const { id } = params
      if (!id) return
      const res = await this.$api.tenantRole.detail({
        id
      })
      const { roleName, roleCode, remark, menuList } = res.data
      this.formData = { roleName, roleCode, id, remark }
      // eslint-disable-next-line eqeqeq
      this.menuDefaultChecked = menuList.map((e) => e.menuId) || []
    },
    // 保存租户角色
    async submitTenantRole(params) {
      const apiName = this.popData.id ? 'roleUpdate' : 'roleAdd'
      const typeName = this.popData.id ? '修改' : '新增'
      const res = await this.$api.tenantRole[apiName]({
        ...params,
        id: this.popData.id
      })
      if (res.code === '1000') {
        this.$message.success(`${typeName}成功！`)
        this.$emit('onFinish', 'add-role')
      } else {
        console.log(`${typeName}异常`)
      }
    },
    /**
     * 提交
     */
    submit() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          // 获取选中的菜单权限列表
          const checkedKeys = this.$refs.myTree.getCheckedKeys() || []
          const halfCheckedKeys = this.$refs.myTree.getHalfCheckedKeys() || []
          const menuCheckKeys = [...checkedKeys, ...halfCheckedKeys].map(
            (e) => {
              return { menuId: e }
            }
          )
          if (!menuCheckKeys.length) {
            this.$message.warning('功能权限不能为空')
            return
          }
          const params = {
            ...this.formData,
            menuList: menuCheckKeys
          }
          this.submitTenantRole(params)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /** 查询所有权限菜单 */
    async queryAllMenu() {
      this.loading = true
      try {
        const res = await this.$api.menuManage.queryAllMenu({})
        if (res.code === '1000') {
          this.treeData = arr2tree(res.data, {
            id: 'id',
            parentId: 'parentId',
            childrenKey: 'children'
          })
        }
      } catch (error) {
        console.log(error)
      }
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.add-box {
  color: #333;
  display: flex;
  max-height: 50vh;
  border: 1px solid #e7e7e7;

  .permiss-box {
    display: flex;
    flex-direction: column;
    padding: 14px;
    width: 50%;
    border-right: 1px solid #e7e7e7;

    .title {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
    }
    .el-form {
      margin-top: 16px;
    }
  }

  .data-limit-box {
    flex: 1;
  }

  .menu-info {
    margin-top: 14px;
    flex: 1;
    overflow-y: auto;
  }

  .data-info {
    margin-top: 14px;
    flex: 1;
    overflow-y: auto;
  }

  .limit-select {
    margin-top: 14px;
  }

  .limit-title {
    margin-right: 14px;
  }
}
</style>
